<template>
  <div class="workdrawing-container">
    <div style="padding: 10px; display: flex;align-items: center;justify-content: space-between;">
      <div style="display: flex;align-items: center;">
        <el-button type="primary" icon="el-icon-document-add" size="small" @click="createBus">导入</el-button>
        <el-tag style="margin-left:10px;">已选：{{multipleSelection.length}}</el-tag>
        <el-button type="primary" icon="el-icon-document-add" size="small" @click="putDroduction" style="margin-left:10px;">排产</el-button>
        <el-button type="primary" icon="el-icon-document-add" size="small" @click="putDroductionFACut">推送到FACut</el-button>
        <el-button type="warning" icon="el-icon-refresh" size="small" @click="reset">列表重置</el-button>
      </div>
      <div style="display: flex;align-items: center;">

        <el-button type="danger" icon="el-icon-document-add" size="small" @click="delAllSelection">删除</el-button>
        <!-- <el-button type="primary" icon="el-icon-document-add" size="small" @click="createBus">排样</el-button>
        
        <el-button type="primary" icon="el-icon-document-add" size="small" @click="createBus">导出</el-button> -->
      </div>
      <div style="width:10px;height:10px;">
        <!-- <el-button-group>
          <el-tooltip class="item" effect="dark" content="列表" placement="top-end">
            <el-button size="mini" type="primary" icon="el-icon-s-operation"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="缩略图" placement="top-end">
            <el-button size="mini" icon="el-icon-s-grid"></el-button>
          </el-tooltip>
        </el-button-group> -->
      </div>
    </div>
    <el-row :gutter="10">
      <el-col :span="4">
        <div class="drawing-catalog">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <div class="scrollbar drawing-catalog-group">
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="(item,index) in tabList" :label="item.value" :key="index">{{item.label}}({{item.childer.length}})</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </el-col>
      <el-col :span="20">
        <el-table :data="tableData" style="width: 100%" height="80vh" ref="filterTable" border @selection-change="handleSelectionChange" v-loading="loading">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column width="120" trigger="click" align="center" show-overflow-tooltip>
            <template slot="header">
              <header-filter title="排样名称" :current-sort="currentSort" props="name" :filter-change="filterChange" :filters="filters.name" />
            </template>
            <template slot-scope="scope">{{ scope.row.name}}</template>
          </el-table-column>
          <el-table-column width="120" trigger="click" align="center" show-overflow-tooltip>
            <template slot="header">
              <header-filter title="排版名称" :current-sort="currentSort" props="subName" :filter-change="filterChange" :filters="filters.subName" />
            </template>
            <template slot-scope="scope">{{ scope.row.subName }}</template>
          </el-table-column>
          <el-table-column label="缩略图" align="center">
            <template slot-scope="scope">
              <el-image style="width: 50px; height: 50px" :src="getAssteImage(scope.row.previewUrl)" fit="contain" :preview-src-list="[getAssteImage(scope.row.previewUrl)]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column width="150" align="center">
            <template slot="header">
              <header-filter title="尺寸(X*Y)(mm)" :current-sort="currentSort" props="spec" :filter-change="filterChange" :filters="filters.spec" />
            </template>
            <template slot-scope="scope">
              {{scope.row.spec}}
            </template>
          </el-table-column>

          <el-table-column width="100" align="center">
            <template slot="header">
              <header-filter title="材料" :current-sort="currentSort" props="material" :filter-change="filterChange" :filters="filters.material" />
            </template>
            <template slot-scope="scope">{{ scope.row.material }}</template>
          </el-table-column>
          <el-table-column width="120" align="center">
            <template slot="header">
              <header-filter title="厚度(mm)" :current-sort="currentSort" sortable props="thick" :filter-change="filterChange" :filters="filters.thick" />
            </template>
            <template slot-scope="scope">
              {{ scope.row.thick}}
            </template>
          </el-table-column>
          <el-table-column width="80" label="气体" align="center">
            <template slot-scope="scope">空气</template>
          </el-table-column>
          <el-table-column width="100" align="center">
            <template slot="header">
              <header-filter title="零件数量" :current-sort="currentSort" sortable props="layoutPartTotal" :filter-change="filterChange" />
            </template>
            <template slot-scope="scope">
              {{scope.row.layoutPartTotal}}
            </template>
          </el-table-column>
          <el-table-column width="100" align="center">
            <template slot="header">
              <header-filter title="利用率" :current-sort="currentSort" sortable props="usedRate" :filter-change="filterChange" />
            </template>
            <template slot-scope="scope">{{ scope.row.usedRate | usedRateText}}%</template>
          </el-table-column>
          <el-table-column width="100" align="center">
            <template slot="header">
              <header-filter title="数量" :current-sort="currentSort" sortable props="usedStockTotal" :filter-change="filterChange" />
            </template>
            <template slot-scope="scope">
              {{scope.row.usedStockTotal}}
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination layout="sizes,total, prev, pager, next, jumper" :current-page="query.page" :page-size="query.pageSize" :page-sizes="[10, 50, 100, 150, 200]" @size-change="handleSizeChange" :total="total" @current-change="handlePageChange"></el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="设备选择" :visible.sync="openMachine" width="500px" append-to-body :close-on-click-modal="false" top="4%">
      <machine :machine.sync="machines" :show="openMachine" />
      <span slot="footer" class="dialog-footer" style="padding-top:10px;">
        <el-button @click="openMachine=false">取 消</el-button>
        <el-button type="primary" @click="submitMethod">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="工厂选择" :visible.sync="openOrganization" width="500px" append-to-body :close-on-click-modal="false" top="4%">
      <organization :organization.sync="organizations" :show="openOrganization" />
      <span slot="footer" class="dialog-footer" style="padding-top:10px;">
        <el-button @click="openOrganization=false">取 消</el-button>
        <el-button type="primary" @click="submitMethod">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import { mapState } from 'vuex';
import Machine from '@/components/machine/Machine.vue';
import Organization from '@/components/machine/Organization.vue';
import HeaderFilter from '@/components/headerFilter/HeaderFilter.vue';
import Workscheduling from './Workscheduling.vue';
import { uniq, findIndex, clone, orderBy, isNumber, sumBy, uniqBy, find, isString } from 'lodash';
import globalJs from '@/utils/global';
export default {
  name: 'Workresult',
  components: { Machine, Workscheduling, HeaderFilter, Organization },
  data() {
    return {
      currentSort: '',
      machines: null,
      organizations: null,
      keyword: '',
      tabList: [],
      tableData: [],
      sourceData: [],
      openMachine: false,
      openOrganization: false,
      loading: false,
      isList: true,
      addOpen: false,
      uploadWork: {},
      uploadFrom: {},
      fileUrl: '',
      taskId: '',
      filters: {
        name: [],
        material: [],
        spec: [],
        thick: [],
        subName: []
      },
      filterVals: {
        name: [],
        material: [],
        spec: [],
        thick: [],
        subName: []
      },
      query: {
        page: 1,
        pageSize: 50
      },
      total: 0,
      multipleSelection: [],
      checkAll: false,
      checkedCities: [],
      isIndeterminate: true
    };
  },
  computed: {
    ...mapState({
      checkTaskIds: (state) => state.app.checkTaskIds,
      checkTasks: (state) => state.app.checkTasks,
      CADLayoutPath: (state) => state.app.CADLayoutPath,
    }),
  },
  filters: {
    formDate: (val) => {
      return global.getdate1(val);
    },
    usedRateText: (val) => {
      if (isNumber(Number(val))) {
        return (val * 100).toFixed(2)
      }
      return 0
    }
  },
  watch: {
    checkTaskIds: {
      deep: true,
      handler: function (val) {
        if (val.length > 0) {
          this.initAjaxMethod();
        } else {
          this.resetSearch();
          this.isIndeterminate = false;
          this.checkedCities = false;
          this.checkAll = [];
          this.tabList = [];
          this.total = 0;
          this.tableData = [];
        }
      },
    },
    CADLayoutPath: {
      deep: true,
      handler: function (val) {
        if (val.length > 0) {
          this.initAjaxMethod();
        }
      },
    },
  },
  mounted() {
    if (this.checkTaskIds.length > 0) {
      this.initAjaxMethod();
    }
  },
  methods: {
    initAjaxMethod() {
      this.loading = true;
      this.$http
        .get(this.$API.GET_LAYOUT + '?' + this.checkTaskIds.map(o => 'taskIds=' + o).join('&'))
        .then((res) => {
          this.loading = false;
          let list = Array.isArray(res.data) ? res.data : [];
          console.log('list', list);
          list.forEach(item => {
            item.spec = item.width + '*' + item.length;
            item.layoutPartTotal = Array.isArray(item.layoutParts) ? this.layoutParts(item.layoutParts, item.id, 1) : 0;
            item.usedStockTotal = Array.isArray(item.usedStocks) ? this.layoutParts(item.usedStocks, item.id, 2) : 0;
          })
          this.filterList(list);
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    filterList(list) {
      let tabs = [];
      list.forEach(item => {
        tabs.push({
          material: item.material,
          thick: item.thick,
          gas: item.gas,
          value: item.material + '-' + item.thick + '-' + item.gas,
          label: this.getPaneLabel(item),
          childer: [],
        });
      });
      let uniqTabs = uniqBy(tabs, o => o.value);
      uniqTabs.forEach(item => {
        list.forEach(val => {
          if (item.material === val.material && item.thick === val.thick) {
            item.childer.push(val);
          }
        });
      });

      if (uniqTabs.length > 0) {
        this.tabList = uniqTabs;
        this.checkAll = true;
        this.handleCheckAllChange(true);
      }
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.tabList.map(o => o.value) : [];
      this.isIndeterminate = false;
      this.$store.dispatch('app/clearTableHeaderFilter');
      this.currentSort = '';
      this.getCheckBoxList();
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tabList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tabList.length;
      this.$store.dispatch('app/clearTableHeaderFilter');
      this.currentSort = '';
      this.getCheckBoxList();
    },
    getCheckBoxList() {
      let childers = [];
      this.tabList.forEach(item => {
        let cIndex = findIndex(this.checkedCities, o => o == item.value);
        if (cIndex >= 0) {
          childers = [...item.childer, ...childers]
        }
      });
      this.orignData = childers;
      this.handleClick();
    },
    handleClick() {
      let material = [], spec = [], name = [], subName = [], thick = [];
      this.orignData.forEach(item => {
        material.push(item.material);
        spec.push(item.spec);
        name.push(item.name);
        subName.push(item.subName);
        thick.push(item.thick);
      });
      this.filters.material = uniq(material).map(o => { return { text: o, value: o }; });
      this.filters.spec = uniq(spec).map(o => { return { text: o, value: o }; });
      this.filters.name = uniq(name).map(o => { return { text: o, value: o }; });
      this.filters.subName = uniq(subName).map(o => { return { text: o, value: o }; });
      this.filters.thick = uniq(thick).map(o => { return { text: o, value: o }; });
      this.filterHandler();
    },
    filterChange(code, type, value) {
      if (type === 'checkBox') {
        if (code === 'name') {
          this.filterVals.name = value;
        } else if (code === 'material') {
          this.filterVals.material = value;
        } else if (code === 'thick') {
          this.filterVals.thick = value;
        } else if (code === 'spec') {
          this.filterVals.spec = value;
        } else if (code === 'subName') {
          this.filterVals.subName = value;
        }
        // console.log('this.filterVals',this.filterVals); 
        this.filterHandler();
      } else if (type === 'sort') {
        this.currentSort = code;
        if (code === 'thick') {
          this.sourceData = orderBy(clone(this.sourceData), 'thick', value);
        } else if (code === 'layoutPartTotal') {
          this.sourceData = orderBy(clone(this.sourceData), 'layoutPartTotal', value);
        } else if (code === 'usedRate') {
          this.sourceData = orderBy(clone(this.sourceData), 'usedRate', value);
        } else if (code === 'usedStockTotal') {
          this.sourceData = orderBy(clone(this.sourceData), 'usedStockTotal', value);
        }
        this.limitMethod();
      }

    },
    filterHandler() {
      let names = [], materials = [], thicks = [], specs = [], subNames = [];
      let { name, material, thick, spec, subName } = this.filterVals;
      if (name.length > 0) {
        this.orignData.forEach(item => {
          let namesIndex = findIndex(name, o => o == item.name);
          if (namesIndex > -1) {
            names.push(item);
          }
        });
      } else {
        names = this.orignData;
      }

      if (material.length > 0) {
        names.forEach(item => {
          let materialsIndex = findIndex(material, o => o == item.material);
          if (materialsIndex > -1) {
            materials.push(item);
          }
        });
      } else {
        materials = names;
      }

      if (thick.length > 0) {
        materials.forEach(item => {
          let thicksIndex = findIndex(thick, o => o == item.thick);
          if (thicksIndex > -1) {
            thicks.push(item);
          }
        });
      } else {
        thicks = materials;
      }

      if (spec.length > 0) {
        thicks.forEach(item => {
          let specsIndex = findIndex(spec, o => o == item.spec);
          if (specsIndex > -1) {
            specs.push(item);
          }
        });
      } else {
        specs = thicks;
      }

      if (subName.length > 0) {
        specs.forEach(item => {
          let subNamesIndex = findIndex(subName, o => o == item.subName);
          if (subNamesIndex > -1) {
            subNames.push(item);
          }
        });
      } else {
        subNames = specs;
      }

      this.sourceData = subNames;
      this.total = subNames.length;
      this.handlePageChange(1);
    },
    layoutParts(paths, id, flag) {
      let num = 0;
      paths.forEach(o => {
        if (o.layoutId == id) {
          num += o.numVal;
        }
      })
      return num;
    },
    createBus() { },
    addPart() {
      if (!Array.isArray(this.checkTasks) || this.checkTasks.length == 0) {
        return this.$message.error('请选择一个作业');
      }
      if (this.checkTasks.length > 1) {
        return this.$message.error('只能选择一个作业,请勿多选');
      }
      this.taskId = this.checkTasks[0].id;
      this.$hubClient.sendCreatePart(this.taskId);
      this.$message.success('数据已发送');
      // this.addOpen = true;
    },
    submitAdd() {
      if (!this.taskId) return this.$message.error('请选择一个作业');
      this.$hubClient.sendCreatePart(this.taskId);
      this.$message.success('数据已发送');
      this.addOpen = false;
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    stockLayout(a, b) {
      if (this.multipleSelection.length == 0) return this.$message.error('请选择一个零件');
      this.openScheduling = true;
    },

    //重置
    reset() {
      this.resetSearch();
      this.handleCheckAllChange(true);
    },
    resetSearch(){
      this.$store.dispatch('app/clearTableHeaderFilter');
      this.currentSort = '';
      this.query.page=1;
    },
    delAllSelection() {
      if (this.multipleSelection.length <= 0) return this.$message.error('请选择一个删除项');
      this.handleDelete(this.multipleSelection[0].id);
    },
    changeStatus(item) {
      console.log('item', item);
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ZHACTIVE_STATUS, {
          id: item.id,
          status_show: item.status_show_switch == true ? 0 : 1,
        })
        .then((res) => {
          loading.close();
          if (res.code == 1) {
            this.$message.success('操作成功!');
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(res.msg);
        });
    },
    //删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const loading = this.$loading({ text: '加载中...' });
        this.$http.del(this.$API.PRODUCTION + '/' + id).then((res) => {
          loading.close();
          this.$message.success('删除成功!');
          this.initAjaxMethod();
        }).catch(err => {
          loading.close();
        })
      });
    },
    //点击第几页
    handlePageChange(currentPage) {
      this.query.page = currentPage;
      this.limitMethod();
    },
    //点击第几页
    handleSizeChange(currentPage) {
      this.query.pageSize = currentPage;
      this.limitMethod();
    },
    limitMethod() {
      let list = [], { page, pageSize } = this.query;
      for (let i = 0; i < this.sourceData.length; i++) {
        if (i >= ((page - 1) * pageSize) && i < (page * pageSize)) {
          list.push(this.sourceData[i]);
        }
      }
      this.tableData = list;
    },
    getPaneLabel(val) {
      let gasName = '';
      if (val.gas == 0) {
        gasName = '空气';
      }
      return `${val.material}-${val.thick}mm-${gasName}`;
    },
    getAssteImage(url) {
      return url && isString(url) ? (globalJs.isAbsolutePath(url) ? url : this.$API.ASSERT_SERVER_URL + url) : '';
    },
    submitMethod() {
      if (this.droductionType == 1) {
        if (!this.organizations) return this.$message.error('请选择一个工厂');
        this.loading = true;
        this.$http
          .put(this.$API.PUT_PRODUCTION, { layoutId: this.multipleSelection[0].id, organizationId: this.organizations.id })
          .then((res) => {
            this.$message.success('操作成功');
            this.loading = false;
            this.openOrganization = false;
            this.initAjaxMethod();
          })
          .catch((err) => {
            this.loading = false;
          });
      } else {
        if (!this.machines) return this.$message.error('请选择一个设备');
        this.loading = true;
        this.$http
          .put(this.$API.PUT_PRODUCTION, { layoutId: this.multipleSelection[0].id, organizationId: this.machines.organizationId })
          .then((res) => {
            this.$message.success('操作成功');
            this.loading = false;
            this.openMachine = false;
            this.initAjaxMethod();
          })
          .catch((err) => {
            this.loading = false;
          });
      }
    },
    putDroduction() {
      if (this.multipleSelection.length != 1) return this.$message.error('请选择一个项目');
      this.droductionType = 1;
      this.organizations = null;
      this.openOrganization = true;
    },
    putDroductionFACut() {
      if (this.multipleSelection.length != 1) return this.$message.error('请选择一个项目');
      this.droductionType = 2;
      this.machines = null;
      this.openMachine = true;
    },
  },
};
</script>

